<?php

namespace App\Http\Controllers\Api;

use App\Category;
use App\Goods;
use App\Http\Requests\StoreGoods;
use App\SpecGoodsPrice;
use function foo\func;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : $this->orderBy;
        $orderType = $request->order_type ? $request->order_type : $this->orderType;
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = Goods::orderBy($orderBy, $orderType);
        if ($request->name) {
            $lists->where('name', 'like', '%'.$request->name.'%');
        }
        if ($request->is_on_sale) {
            $lists->where('is_on_sale', $request->get('is_on_sale'));
        }
        if ($request->category_id) {
            $lists->where('category_id', $request->category_id);
        }
        if ($request->get('jifenshop')) {
            $ids = Category::where('parent_id', 9)->pluck('id');
            $lists->whereIn('category_id', $ids);
        }
        if ($request->get('column')  == 'ypy') {
            $lists->where('category_id', 3);
        }
        if ($request->get('column')  == 'ypg') {
            $lists->where('category_id', '<>' ,3);
        }
        if ($request->get('promotion')) {
            // 限时秒杀
            if ($request->get('promotion') == 'flash_sale') {
                $lists->whereHas('flashSale', function($query) {
                    return $query->ofUnderway();
                })->with('underwayFlashSale');
            }

            if ($request->get('promotion') == 'team_activity') {
                $lists->whereHas('teamActivity', function($query) {
                    return $query->ofActive();
                })->with('underwayTeamActivity');
            }

            if ($request->get('promotion') == 'full_cut') {
                $lists->whereNotNull('full_cut');
            }

            if ($request->get('promotion') == 'integral') {
                $lists->where('exchange_integral', '>', 0);
            }
        }
        return $lists->with(['category', 'attrs', 'specPrices'])->paginate($pageSize);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param StoreGoods $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(StoreGoods $request)
    {
        $data = $request->except(['content', 'attrs', 'attachments']);
        $goods = Goods::create($data);
        $goods->content()->create([]);
        return response($goods);
    }

    /**
     * @param Goods $good
     * @return Goods
     */
    public function show(Request $request, Goods $good)
    {
        // 商品内容
        $good->content = $good->content()->value('body');
        // 商品附件（相册）
        $good->attachments = $good->attachments()->pluck('url');
        // 商品评价
        $good->comments = $good->comments()->latest()->where('is_show', 1)->with(['user' => function($query) {
            return $query->select('id', 'name', 'avatar');
        }])->with(['orderGoods'])->limit(2)->get();
        //商品规格
        $good->specs = SpecGoodsPrice::byGoods($good->id);
        // 商品属性
        $good->attrs;
        $good->underwayFlashSale;
        if ($good->underwayTeamActivity) {
            $good->underwayTeamActivity->activeFounds;
        }
        $specPrices = SpecGoodsPrice::where('goods_id', $good->id)->get();
        $good->spec_prices = $specPrices->keyBy('key');
        // 推荐商品
        if ($request->references) {
            $good->references = Goods::where('category_id', $good->category_id)->where('id', '<>', $good->id)->orderBy('sales_count')->limit(10)->get();
        }
        return $good;
    }

    /**
     * @param Goods $good
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function edit(Goods $good)
    {
        $good->content = $good->content;
        $good->attrs = $good->attrs;
        $good->attachments = $good->attachments;
        return response($good);
    }

    /**
     * @param Request $request
     * @param Goods $good
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function update(Request $request, Goods $good)
    {
        $good->update($request->except(['content', 'attrs', 'attachments']));
        // 保存商品信息
        if ($request->has('content')) {
            $good->content->body = $request->get('content')['body'];
            $good->content->save();
        }
        return response($good);
    }

    /**
     * @param Goods $good
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function destroy(Goods $good)
    {
        $good->delete();
        return response(['message' => '删除成功']);
    }

    /**
     * 更新商品属性，商品规格
     * @param Request $request
     * @param Goods $good
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function updateGoodsAttr(Request $request, Goods $good)
    {
        // 更新商品模型
        $good->type_id = $request->type_id;
        $good->save();

        // 更新商品属性
        $attrs = [];
        foreach ($request->attrs as $attr) {
            if ($attr['value']) {
                $attrs[$attr['id']]['value'] = $attr['value'];
                $attrs[$attr['id']]['name'] = $attr['name'];
            }
        }
        $good->attrs()->sync($attrs);

        // 更新商品规格
        $specPrices = $request->specPrices;
        SpecGoodsPrice::where('goods_id', $good->id)->delete(); // 删除旧数据
        if ($specPrices) {
            foreach ($specPrices as $specPrice) {
                $good->specPrices()->create($specPrice);
            }
        }
        return response(['message' => '创建成功']);
    }

    public function history(Request $request)
    {
        if ($request->history) {
            $history = explode(',', $request->history);
            $goods = Goods::whereIn('id', $history)->get();
            $list = [];
            if ($goods) {
                foreach ($history as $v) {
                    foreach ($goods as $g) {
                        if ($g['id'] == $v) {
                            array_push($list, $g);
                        }
                    }
                }
            }
            return $list;
        }
        return [];
    }
}
